﻿
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Winton.Extensions.Configuration.Consul;

namespace Micro.Core.Service.ConsulConfig
{
    /// <summary>
    /// Consul 配置中心
    /// </summary>
    public class ConsulConfigCenter : IConfigCenter
    {
        public void LoadConfigCenter(WebHostBuilderContext context, IConfigurationBuilder config)
        {
            // 1、加载配置中心配置文件
            IConfiguration configuration = config.AddJsonFile("config-center.json", false, true).Build(); // 动态监听配置文件改变

            var configFolder = configuration["ConfigFolder"];
            // 2、取值
            string configCenter = configuration["ConfigCenter"];

            // 3、加载consul配置文件
             var webHostEnvironment = context.HostingEnvironment;

            var key =  $"{configFolder}{webHostEnvironment.ApplicationName}.{webHostEnvironment.EnvironmentName}.json";
            config.AddConsul(key, options =>
            {
                options.ConsulConfigurationOptions = cco =>
                {
                    cco.Address = new Uri(configCenter);
                };

                // 1、热加载配置文件
                options.ReloadOnChange = true;
            });
        }
    }
}
